<template>
	<xn-form-container
		:title="formData.id ? '编辑模板' : '新增模板'"
		:width="700"
		v-model:open="open"
		:destroy-on-close="true"
		@close="onClose"
	>
	    <!-- <a-alert v-if="!formData.templateName" class="mb-3" message="请填写模板名称" type="warning" show-icon /> -->
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="模板名称：" name="templateName">
				<a-input v-model:value="formData.templateName" placeholder="请输入模板名称" allow-clear />
			</a-form-item>
			<a-form-item label="模板类型：" name="templateType">
				<a-select v-model:value="formData.templateType" placeholder="请选择模板类型" :options="templateTypeOptions"/>
			</a-form-item>
			<a-form-item label="触发方式：" name="triggerMode">
				<a-select v-model:value="formData.triggerMode" placeholder="请选择触发方式" :options="triggerModeOptions"/>
			</a-form-item>
			<a-form-item label="触发时间(分)：" name="timeSlot">
				<a-input style="height: 36px;" v-model:value="formData.timeSlot" placeholder="请输入触发时间" allow-clear />
			</a-form-item>
		</a-form>
        
		<a-alert v-if="showError" class="mb-3" message="请选择需要配置的算法" type="warning" show-icon />
		<a-collapse v-model:activeKey="activeKey" @change="handleCollapseChange">
			<a-collapse-panel v-for="(item, index) in formData.algorithmConfigParams" :key="item.value" :header="item.label">
			  <!-- 自定义标题，包含Checkbox -->
	          <template #extra>
				<a-checkbox @click.native.stop="onCheckboxClick" v-model:checked="item.checked" v-model:value="item.checked" @change="handleCheckboxChange(index, $event)">
     			</a-checkbox>
			  </template>
              
			  <!-- 神经控制 -->
			  <template v-if="item.value === '1'">
				<a-form ref="formRef" :model="item" :rules="formRules" layout="horizontal" :label-col="labelCol">
					<a-form-item label="调控时间(秒)：" name="duration">
						<a-input v-model:value="item.duration" placeholder="请输入调控时间,范围:60~7200" allow-clear />
				    </a-form-item>
					<a-form-item label="调控模式：" name="mode">
						<a-select v-model:value="item.mode" placeholder="请选择调控模式" :options="neuralRegulationOptions" @change="handleModeChange"/>
					</a-form-item>
					<a-form-item label="波形幅度(amp)：" name="amp">
						<a-input v-model:value="item.amp" placeholder="请输入波形幅度"  allow-clear />
					</a-form-item>
					<a-form-item label="调控频率(frq)：" name="frq">
						<a-input v-model:value="item.frq" placeholder="请输入调控频率"  allow-clear />
					</a-form-item>
				</a-form>
			  </template>

			  <!-- 节拍振子助眠 -->
			  <template v-if="item.value === '2'">
				<a-form ref="formRef" :model="item" :rules="formRules" layout="horizontal" :label-col="labelCol">
					<a-form-item label="助眠时间(秒)：" name="duration">
						<a-input v-model:value="item.duration" placeholder="请输入助眠时间,范围:600~3600" allow-clear />
				    </a-form-item>
					<a-form-item label="选项：" name="source">
						<a-select v-model:value="item.source" placeholder="请选择振子选项" :options="beatOscillatorOptions" @change="handleModeChange"/>
					</a-form-item>
					<a-form-item label="震动强度：" name="density">
						<a-input v-model:value="item.density" placeholder="请输入震动强度"  allow-clear />
					</a-form-item>
				</a-form>
			  </template>

			  <!-- 音频助眠 -->
			  <template v-if="item.value === '3'">
				<a-form ref="formRef" :model="item" :rules="formRules" layout="horizontal" :label-col="labelCol">
					<a-form-item label="助眠时间(秒)：" name="duration">
						<a-input v-model:value="item.duration" placeholder="请输入助眠时间,范围:0~3600" allow-clear />
				    </a-form-item>
					<a-form-item label="音频文件：" name="source">
						<a-select clearable v-model:value="item.source" mode="tags" placeholder="请选择音频文件" :options="sourceOptions">
							<!-- <a-option
								v-for="sourceItem in sourceOptions"
								:key="sourceItem.id"
								:title="sourceItem.downloadPath"
								:value="sourceItem.id"
								:label="sourceItem.name"
							/> -->
						</a-select>
					</a-form-item>
					<a-form-item label="播放音量：" name="volume">
						<a-input v-model:value="item.volume" placeholder="请输入播放音量范围"  allow-clear />
					</a-form-item>
				</a-form>
			  </template>

			  <!-- 双声拍助眠 -->
			  <template v-if="item.value === '4'">
				<a-form ref="formRef" :model="item" :rules="formRules" layout="horizontal" :label-col="labelCol">
					<a-form-item label="助眠时间(秒)：" name="duration">
						<a-input v-model:value="item.duration" placeholder="请输入助眠时间,范围:600~3600" allow-clear />
				    </a-form-item>
					<a-form-item label="音频文件：" name="source">
						<a-select clearable v-model:value="item.source" mode="tags" placeholder="请选择音频文件" :options="sourceOptions" />
					</a-form-item>
					<a-form-item label="播放音量：" name="volume">
						<a-input v-model:value="item.volume" placeholder="请输入播放音量范围"  allow-clear />
					</a-form-item>
				</a-form>
			  </template>

			  <!-- LED灯带控制 -->
			  <template v-if="item.value === '5'">
				<a-form ref="formRef" :model="item" :rules="formRules" layout="horizontal" :label-col="labelCol">
					<a-form-item label="发光总时间(秒)：" name="duration">
						<a-input v-model:value="item.duration" placeholder="请输入灯带发光总时间,范围:0~3600" allow-clear />
				    </a-form-item>
					<a-form-item label="发光周期(秒)：" name="term">
						<a-input v-model:value="item.term" placeholder="请输入发光变化周期的时长,小于发光总时间" allow-clear />
				    </a-form-item>
					<a-form-item label="发光模式：" name="mode">
						<a-select v-model:value="item.mode" placeholder="请选择发光模式" :options="ledModeOptions" @change="handleModeChange"/>
					</a-form-item>
					<a-form-item label="起点颜色：" name="scolor">
						<color-picker v-model:value="item.scolor" />
					</a-form-item>
					<a-form-item label="终点颜色：" name="ecolor">
					    <color-picker v-model:value="item.ecolor" />
					</a-form-item>
				</a-form>
			  </template>			  		  
			</a-collapse-panel>
		</a-collapse>

		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="algorithmConfigForm">
    import ColorPicker from '@/components/ColorPicker/index.vue'
    import { Modal } from 'ant-design-vue';
	import tool from '@/utils/tool'
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import algorithmConfigApi from '@/api/biz/algorithmConfigApi'
	import algorithmFileApi from '@/api/biz/algorithmFileApi'

	const color = ref('');
	const labelCol = { span: 4 }
	const showError = ref(false)
	// 抽屉状态
	const open = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref(null)
	// 表单数据
	const formData = ref({
		id: '',
		templateName: '',
		templateType: '', // 模板类型
		triggerMode: '', // 触发方式
		timeSlot: '', // 触发时间
		algorithmConfigParams: []
	})
	const submitLoading = ref(false)
	const nameOptions = ref([])
	const sourceOptions = ref([])
    
	// 算法选项
	const activeKey = ref([])
	const algorithmOptions = ref([])

	// 算法点击事件
	const onCheckboxClick = () =>{}
	const handleCheckboxChange = (index, event) => {
    //   items.value[index].checked = event.target.checked;
    }
    
	// 折叠面板改变事件
	const handleCollapseChange = (keys) => {
		for(let item of formData.value.algorithmConfigParams){
			if(keys.includes(item.value)){
				item.checked = true
			}
		}
	}
    
	// 神经调控模式选项
	const neuralRegulationOptions = ref([])	
    // 节拍振子选项
	const beatOscillatorOptions = ref([])	
	// LED模式选项
	const ledModeOptions = ref([])	

	// 模板类型选项
	const templateTypeOptions = ref([])	
	// 触发方式选项
	const triggerModeOptions = ref([])	

	// 组件挂载时获取文件资源数据
	onMounted(() => {
		fetchSourceOptions();
	});
	
    // 获取音频文件
	const fetchSourceOptions = async () => {
		try {
			const response = await algorithmFileApi.algorithmFileList(); 
			// debugger
			for(let item of response){
				item.value = item.id
				item.label = item.name
			}
			sourceOptions.value = response; 
		} catch (error) {
			console.error('Failed to fetch source options:', error);
		}
	};

	// 初始化算法选项
	const initAlgorithmOptions = async () => {
		try {
			algorithmOptions.value = tool.dictList('algorithmControl')
			for(let item of algorithmOptions.value){
				item.checked = false
				item.name = item.label
				item.type = item.value
				item.duration = ''
				item.mode = ''
				item.amp = ''
				item.frq = ''
				item.source = []
				item.density = ''
				item.volume = ''
				item.term = ''
				item.scolor = ''
				item.ecolor = ''
			}
			formData.value.algorithmConfigParams = algorithmOptions.value
			activeKey.value = []
		} catch (error) {
			console.error('Failed to fetch source options:', error);
		}
	};
    
	// 获取算法详情
	const getDetail = async(id) => {
		try {
			const res = await algorithmConfigApi.algorithmTemplateDetail({id})
			if(res && res.length > 0){
				const activeAlgorithm = []
				for(let template of formData.value.algorithmConfigParams){
					for(let item of res){
						if(template.type === item.type){	
							template.checked = true		
							template.duration = item.duration
							template.mode = item.mode
							template.amp = item.amp
							template.frq = item.frq
							template.source = item.source
							template.density = item.density
							template.volume = item.volume
							template.term = item.term
							template.scolor = item.scolor
							template.ecolor = item.ecolor		
							if(item.source && (item.type === '3' || item.type === '4')){
								template.source = item.source.split(',')
							}	
							if(!item.source) template.source = []
							activeAlgorithm.push(template.type)
							break
						}
					}
				}
				activeKey.value = activeAlgorithm		
			}
			return res
		} catch (error) {}
	}

	// 打开抽屉
	const onOpen = async(record) => {
		open.value = true
		await initAlgorithmOptions();
		if (record) {
			// let recordData = cloneDeep(record)
			// formData.value = Object.assign({}, recordData)
			formData.value.id = record.id
			formData.value.templateName = record.templateName
			formData.value.templateType = record.templateType
			formData.value.triggerMode = record.triggerMode
			formData.value.timeSlot = record.timeSlot
			await getDetail(record.id)
		}
		fetchSourceOptions();
		nameOptions.value = tool.dictList('algorithmControl')
        neuralRegulationOptions.value = tool.dictList('neuralRegulation')
		beatOscillatorOptions.value = tool.dictList('beatOscillator')
		ledModeOptions.value = tool.dictList('ledMode')
		templateTypeOptions.value = tool.dictList('templateType')
		triggerModeOptions.value = tool.dictList('triggerMode')
	}

	// 关闭抽屉
	const onClose = () => {
		// formRef.value.resetFields()
		formData.value = {}
		open.value = false
	}

	// 处理神经调控模式更改事件
	const handleModeChange = (value) => {

	};

	// 默认要校验的
	const formRules = {
	}

	// 验证并提交数据
	const onSubmit = () => {
		// Modal.info({
		// 	title: '提示',
		// 	content: h('div', {}, [
		// 		h('p', '确定保存？'),
		// 	]),
		// 	cancelText: '取消',
		// 	okText: '确认',
		// 	onOk() {
				
		// 	},
		// });
        const algorithmValues = []
		submitLoading.value = true
		const formDataParam = cloneDeep(formData.value)
		formDataParam.algorithmConfigParams = formDataParam.algorithmConfigParams.filter(item => {
			return item.checked
		});
		
		for(let item of formDataParam.algorithmConfigParams){
			// 格式化音频文件
			if(item.source) item.source = item.source.join()
			algorithmValues.push(item.type)
		}
		// 判断模板名称
		if(!formDataParam.templateName){
			submitLoading.value = false
			alert('请填写模板名称')
			return
		}
		if(algorithmValues.includes('3') && algorithmValues.includes('4')){
			submitLoading.value = false
			alert('音频助眠和双声拍助眠不可同时配置！')
			return
		}
		if(formDataParam.algorithmConfigParams && formDataParam.algorithmConfigParams.length > 0){
			algorithmConfigApi
			.algorithmConfigSubmit(formDataParam, formDataParam.id)
			.then(() => {
				onClose()
				emit('successful')
			})
			.finally(() => {
				submitLoading.value = false
			})
		}
		else{
			alert('请选择需要配置的算法')
			showError.value = true
			submitLoading.value = false
		}
		
		
		// formRef.value
		// 	.validate()
		// 	.then(() => {
		// 		submitLoading.value = true
		// 		// debugger;
		// 		console.log(formData.value)
		// 		const formDataParam = cloneDeep(formData.value)
		// 		algorithmConfigApi
		// 			.algorithmConfigSubmit(formDataParam, formDataParam.id)
		// 			.then(() => {
		// 				onClose()
		// 				emit('successful')
		// 			})
		// 			.finally(() => {
		// 				submitLoading.value = false
		// 			})
		// 	})
		// 	.catch(() => {})
	}
	// 抛出函数
	defineExpose({
		onOpen
	})
</script>
